import SliderWithValue from "@/components/ui/SliderWithValue";
import { MaterialIcons } from "@expo/vector-icons";
import { ResizeMode, Video } from "expo-av";
import * as ImagePicker from "expo-image-picker";
import React, { useRef, useState } from "react";
import {
    Alert,
    Dimensions,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from "react-native";

const { width: screenWidth } = Dimensions.get('window');

interface VideoEditorProps {
  onVideoSelect: (videoData: { 
    source: string; 
    thumbnail: string; 
    width: number; 
    height: number; 
    duration?: number;
  }) => void;
  onVideoTrim?: (startTime: number, endTime: number) => void;
  onVideoSpeed?: (speed: number) => void;
  onVideoVolume?: (volume: number) => void;
}

export const VideoEditor: React.FC<VideoEditorProps> = ({
  onVideoSelect,
  onVideoTrim,
  onVideoSpeed,
  onVideoVolume,
}) => {
  const [selectedVideo, setSelectedVideo] = useState<string | null>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [duration, setDuration] = useState(0);
  const [position, setPosition] = useState(0);
  const [volume, setVolume] = useState(1);
  const [speed, setSpeed] = useState(1);
  const [trimStart, setTrimStart] = useState(0);
  const [trimEnd, setTrimEnd] = useState(0);
  const [activeTab, setActiveTab] = useState<'select' | 'edit' | 'effects'>('select');
  
  const videoRef = useRef<Video>(null);

  // 选择视频
  const handleSelectVideo = async () => {
    try {
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        Alert.alert('权限不足', '需要访问相册权限');
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Videos,
        allowsEditing: false,
        quality: 1,
      });

      if (!result.canceled && result.assets[0]) {
        const asset = result.assets[0];
        setSelectedVideo(asset.uri);
        setTrimEnd(asset.duration || 10000);
        
        onVideoSelect({
          source: asset.uri,
          thumbnail: asset.uri, // 在实际应用中需要生成缩略图
          width: asset.width || 320,
          height: asset.height || 240,
          duration: asset.duration || undefined,
        });
      }
    } catch (error) {
      console.error('选择视频错误:', error);
      Alert.alert('错误', '选择视频失败');
    }
  };

  // 拍摄视频
  const handleRecordVideo = async () => {
    try {
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      if (status !== 'granted') {
        Alert.alert('权限不足', '需要相机权限');
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Videos,
        allowsEditing: false,
        quality: 1,
        videoMaxDuration: 60, // 最长60秒
      });

      if (!result.canceled && result.assets[0]) {
        const asset = result.assets[0];
        setSelectedVideo(asset.uri);
        setTrimEnd(asset.duration || 10000);
        
        onVideoSelect({
          source: asset.uri,
          thumbnail: asset.uri,
          width: asset.width || 320,
          height: asset.height || 240,
          duration: asset.duration || undefined,
        });
      }
    } catch (error) {
      console.error('录制视频错误:', error);
      Alert.alert('错误', '录制视频失败');
    }
  };

  // 播放/暂停
  const togglePlayback = async () => {
    if (videoRef.current) {
      if (isPlaying) {
        await videoRef.current.pauseAsync();
      } else {
        await videoRef.current.playAsync();
      }
      setIsPlaying(!isPlaying);
    }
  };

  // 处理播放状态更新
  const handlePlaybackStatusUpdate = (status: any) => {
    if (status.isLoaded) {
      setDuration(status.durationMillis || 0);
      setPosition(status.positionMillis || 0);
      setIsPlaying(status.isPlaying);
    }
  };

  // 设置播放位置
  const handleSeek = async (positionMs: number) => {
    if (videoRef.current) {
      await videoRef.current.setPositionAsync(positionMs);
      setPosition(positionMs);
    }
  };

  // 应用裁剪
  const handleApplyTrim = () => {
    if (onVideoTrim) {
      onVideoTrim(trimStart, trimEnd);
    }
    Alert.alert('成功', '视频裁剪设置已保存');
  };

  // 应用速度
  const handleSpeedChange = (newSpeed: number) => {
    setSpeed(newSpeed);
    if (onVideoSpeed) {
      onVideoSpeed(newSpeed);
    }
  };

  // 应用音量
  const handleVolumeChange = async (newVolume: number) => {
    setVolume(newVolume);
    if (videoRef.current) {
      await videoRef.current.setVolumeAsync(newVolume);
    }
    if (onVideoVolume) {
      onVideoVolume(newVolume);
    }
  };

  // 渲染选择界面
  const renderSelectTab = () => (
    <View style={styles.selectContainer}>
      <Text style={styles.sectionTitle}>选择视频</Text>
      
      <View style={styles.actionButtons}>
        <TouchableOpacity style={styles.actionButton} onPress={handleSelectVideo}>
          <MaterialIcons name="video-library" size={32} color="#007AFF" />
          <Text style={styles.actionButtonText}>相册选择</Text>
        </TouchableOpacity>
        
        <TouchableOpacity style={styles.actionButton} onPress={handleRecordVideo}>
          <MaterialIcons name="videocam" size={32} color="#007AFF" />
          <Text style={styles.actionButtonText}>录制视频</Text>
        </TouchableOpacity>
      </View>

      {selectedVideo && (
        <View style={styles.previewContainer}>
          <Video
            ref={videoRef}
            style={styles.videoPreview}
            source={{ uri: selectedVideo }}
            resizeMode={ResizeMode.CONTAIN}
            isLooping={false}
            onPlaybackStatusUpdate={handlePlaybackStatusUpdate}
          />
          
          <View style={styles.playbackControls}>
            <TouchableOpacity onPress={togglePlayback} style={styles.playButton}>
              <MaterialIcons 
                name={isPlaying ? "pause" : "play-arrow"} 
                size={24} 
                color="#fff" 
              />
            </TouchableOpacity>
            
            <View style={styles.progressContainer}>
              <Text style={styles.timeText}>
                {Math.floor(position / 1000)}s / {Math.floor(duration / 1000)}s
              </Text>
            </View>
          </View>
        </View>
      )}
    </View>
  );

  // 渲染编辑界面
  const renderEditTab = () => (
    <View style={styles.editContainer}>
      <Text style={styles.sectionTitle}>视频编辑</Text>
      
      {/* 视频裁剪 */}
      <View style={styles.editSection}>
        <Text style={styles.editSectionTitle}>裁剪时长</Text>
        <View style={styles.trimControls}>
          <SliderWithValue
            label="开始时间"
            value={trimStart / 1000}
            minimumValue={0}
            maximumValue={duration / 1000}
            onValueChange={(value) => setTrimStart(value * 1000)}
            suffix="s"
          />
          <SliderWithValue
            label="结束时间"
            value={trimEnd / 1000}
            minimumValue={trimStart / 1000}
            maximumValue={duration / 1000}
            onValueChange={(value) => setTrimEnd(value * 1000)}
            suffix="s"
          />
        </View>
        <TouchableOpacity style={styles.applyButton} onPress={handleApplyTrim}>
          <Text style={styles.applyButtonText}>应用裁剪</Text>
        </TouchableOpacity>
      </View>

      {/* 播放速度 */}
      <View style={styles.editSection}>
        <Text style={styles.editSectionTitle}>播放速度</Text>
        <SliderWithValue
          label="速度"
          value={speed}
          minimumValue={0.5}
          maximumValue={3}
          onValueChange={handleSpeedChange}
          suffix="x"
        />
      </View>

      {/* 音量控制 */}
      <View style={styles.editSection}>
        <Text style={styles.editSectionTitle}>音量</Text>
        <SliderWithValue
          label="音量"
          value={volume * 100}
          minimumValue={0}
          maximumValue={100}
          onValueChange={(value) => handleVolumeChange(value / 100)}
          suffix="%"
        />
      </View>
    </View>
  );

  // 渲染特效界面
  const renderEffectsTab = () => (
    <View style={styles.effectsContainer}>
      <Text style={styles.sectionTitle}>视频特效</Text>
      <View style={styles.comingSoon}>
        <MaterialIcons name="movie-filter" size={48} color="#ccc" />
        <Text style={styles.comingSoonText}>视频特效功能</Text>
        <Text style={styles.comingSoonSubtext}>即将推出</Text>
      </View>
    </View>
  );

  return (
    <View style={styles.container}>
      {/* 标签页 */}
      <View style={styles.tabContainer}>
        {[
          { key: 'select', label: '选择', icon: 'video-library' },
          { key: 'edit', label: '编辑', icon: 'edit' },
          { key: 'effects', label: '特效', icon: 'movie-filter' },
        ].map((tab) => (
          <TouchableOpacity
            key={tab.key}
            style={[styles.tab, activeTab === tab.key && styles.activeTab]}
            onPress={() => setActiveTab(tab.key as any)}
          >
            <MaterialIcons 
              name={tab.icon as any} 
              size={20} 
              color={activeTab === tab.key ? "#007AFF" : "#666"} 
            />
            <Text style={[styles.tabText, activeTab === tab.key && styles.activeTabText]}>
              {tab.label}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* 内容区域 */}
      <View style={styles.content}>
        {activeTab === 'select' && renderSelectTab()}
        {activeTab === 'edit' && renderEditTab()}
        {activeTab === 'effects' && renderEffectsTab()}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#f5f5f5",
  },
  tabContainer: {
    flexDirection: "row",
    backgroundColor: "#fff",
    paddingHorizontal: 10,
    paddingTop: 10,
  },
  tab: {
    flex: 1,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 12,
    borderBottomWidth: 2,
    borderBottomColor: "transparent",
  },
  activeTab: {
    borderBottomColor: "#007AFF",
  },
  tabText: {
    marginLeft: 4,
    fontSize: 14,
    color: "#666",
  },
  activeTabText: {
    color: "#007AFF",
    fontWeight: "600",
  },
  content: {
    flex: 1,
    padding: 20,
  },
  selectContainer: {
    flex: 1,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: "#333",
    marginBottom: 20,
    textAlign: "center",
  },
  actionButtons: {
    flexDirection: "row",
    justifyContent: "space-around",
    marginBottom: 30,
  },
  actionButton: {
    alignItems: "center",
    padding: 20,
    backgroundColor: "#fff",
    borderRadius: 12,
    borderWidth: 1,
    borderColor: "#e0e0e0",
    minWidth: 120,
  },
  actionButtonText: {
    marginTop: 8,
    fontSize: 14,
    color: "#333",
  },
  previewContainer: {
    backgroundColor: "#fff",
    borderRadius: 12,
    overflow: "hidden",
  },
  videoPreview: {
    width: "100%",
    height: 200,
    backgroundColor: "#000",
  },
  playbackControls: {
    flexDirection: "row",
    alignItems: "center",
    padding: 15,
    backgroundColor: "rgba(0,0,0,0.8)",
  },
  playButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: "#007AFF",
    alignItems: "center",
    justifyContent: "center",
    marginRight: 15,
  },
  progressContainer: {
    flex: 1,
  },
  timeText: {
    color: "#fff",
    fontSize: 14,
  },
  editContainer: {
    flex: 1,
  },
  editSection: {
    backgroundColor: "#fff",
    borderRadius: 12,
    padding: 20,
    marginBottom: 15,
  },
  editSectionTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: "#333",
    marginBottom: 15,
  },
  trimControls: {
    marginBottom: 15,
  },
  applyButton: {
    backgroundColor: "#007AFF",
    borderRadius: 8,
    paddingVertical: 12,
    alignItems: "center",
  },
  applyButtonText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "600",
  },
  effectsContainer: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  comingSoon: {
    alignItems: "center",
    padding: 40,
  },
  comingSoonText: {
    fontSize: 18,
    color: "#666",
    marginTop: 15,
  },
  comingSoonSubtext: {
    fontSize: 14,
    color: "#999",
    marginTop: 5,
  },
});
